from __future__ import absolute_import
import logging

logger = logging.getLogger('fengge.debug')

class DatabaseRouter(object):
    model_db_d = {
        'dxuser.DXUserLog':'log',
        # 'dxuser.Invitation':'log',
        'fglog.SnapshotLog': 'log',
        'fglog.PItemLog': 'log',
        'fglog.DownloadLog': 'log',
        'filecache.FileCache':'filecache',
        'filecache.FileCacheBucket':'filecache',
        # 'mapdata.PolygonMap': 'gis',
        # 'mapdata.PointMap': 'gis',
        # 'mapdata.LineMap': 'gis',
    }
    def db_for_read(self, model, **hints):
        model_fullname = '%s.%s' % (model._meta.app_label, model._meta.object_name)
        result = self.model_db_d.get(model_fullname, 'default')
        # logger.debug("db_for_read: %s -> %s" % (model, result))
        return result

    def db_for_write(self, model, **hints):
        model_fullname = '%s.%s' % (model._meta.app_label, model._meta.object_name)
        result = self.model_db_d.get(model_fullname, 'default')
        # logger.debug("db_for_write: %s -> %s" % (model, result))
        return result

    def allow_relation(self, obj1, obj2, **hints):
        model_fullname1 = '%s.%s' % (obj1._meta.app_label, obj1._meta.object_name)
        model_fullname2 = '%s.%s' % (obj2._meta.app_label, obj2._meta.object_name)
        if self.model_db_d.get(model_fullname1, 'default') == \
                self.model_db_d.get(model_fullname2, 'default'):
            result = True
        else:
            result = False
        # logger.debug("allow_relation: %s <> %s -> %s" % (obj1.__class__, obj2.__class__, result))
        return result

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True
        # good_db = self.model_db_d.get(model, 'default')
        # if good_db is None:
        #     if db not in self.model_db_d.values():
        #         result = True
        #     else:
        #         result = False
        # else:
        #     if good_db == db:
        #         result = True
        #     else:
        #         result = False
        # logger.debug("allow_migrate: %s <> %s -> %s" % (db, model, result))
